var createError = require("http-errors");
var express = require("express");
var cors = require("cors");
require("express-async-errors");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var responseFormatter = require("./middleware/responseFormatter.js");
var { expressjwt } = require('express-jwt')
var { secretKey } = require('./common/const')

var indexRouter = require("./routes/index");
var usersRouter = require("./routes/users");
var roomGroupRouter = require("./routes/roomGroup");
var roomRouter = require("./routes/room");

var app = express();

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.set("view engine", "ejs");
// 跨域处理
app.use(cors());
app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(responseFormatter);

app.use(
  expressjwt({ secret: secretKey, algorithms: ["HS256"] }).unless({
    path: ['/users/login'],
  })
)

app.use("/", indexRouter);
app.use("/users", usersRouter);
app.use("/roomGroup", roomGroupRouter);
app.use("/room", roomRouter);

// 全局异常处理
app.use(function (err, req, res, next) {
  result = {
    code: err.status || 500,
    msg: err.message,
  };
  res.send(result);
});

// catch 404 and forward to error handler
app.use(function (req, res, next) {
  res.sendStatus(404);
  // next(createError(404));
});

module.exports = app;
